# Create your views here.
import json
from django.db.models import F
from django.http import JsonResponse
from rest_framework.response import Response
from Blog import models
from rest_framework.views import APIView
from Blog.serializers import TypeSerializer,BlogSerializer,CommtentSerializer,BlogDtailSerializer,BlogHotSerializer
from Blog.util import LimitPagination,DataFailed
from UserProfile.models import User
from django.db import transaction
#继承rest_framework APIView
#新增博客
class BlogPut(APIView):
    #发布博客
    def post(self, request, *args, **kwargs):
        response = {'status': "200", 'msg': '发布成功'}
        #基本数据
        title = request.POST.get('title', None)
        type_id = request.POST.get('type_id', None)
        content = request.POST.get('content', None)
        cover = request.POST.get('cover', None)
        #用户信息

        if cover is None:
            cover = "default/blog.jpg"
        if cover is "":
            cover = "default/blog.jpg"

        user_id = request.user[0]['id']
        user = getUser(user_id)
        type = getType(type_id)
        try:
            obj = models.Blog(title=title, type=type,user=user,cover=cover,content=content)
            obj.save()
        except Exception as e:
            response = {'status': "201", 'msg': '发布异常'}
        return JsonResponse(response,safe=False)

#获取类型
class Type(APIView):
    authentication_classes = []
    def get(self, request, *args, **kwargs):
        #查询Blog_Type表，返回了QuerySet对象
        res = models.Type.objects.all().values('id','name')
        #调用序列化方法，把对象转化为字符串 序列化就是把对象转换成字符串，反序列化就是把字符串转换成对象
        serializer = TypeSerializer(res, many=True)
        result = {'status': "200", 'msg': '获取成功','data':serializer.data}
        #Response返回字符串对象，返回对象报错
        return Response(result)

#获取博客列表
class BlogList(APIView):
    authentication_classes = []
    def get(self, request, *args, **kwargs):
        id = request.GET.get('id', None)
        type_id = request.GET.get('type', None)
        filter_dict = dict()
        filter_dict['status'] = 1
        if id is None:
            #查询Blog_blog表，返回了QuerySet对象
            if type_id is None:
                res = models.Blog.objects.filter(**filter_dict).values('id','type', 'cover','user','title','content', 'is_recommend','ctime','view','comments','goods','collections').order_by('-ctime')
            else:

                type = getType(type_id)
                filter_dict['type'] = type
                res = models.Blog.objects.filter(**filter_dict).values('id','type', 'cover','user','title','content', 'is_recommend','ctime','view','comments','goods','collections').order_by('-ctime')
        #Response返回字符串对象，返回对象报错
        else:
            try:
                blog = models.Blog.objects.get(id=id)
            except:
                raise  DataFailed({"status": "202", "msg": "博客不存在"})
            blog.view = F('view') + 1
            blog.save()
            filter_dict['id'] = id
            res = models.Blog.objects.filter(**filter_dict).values('id', 'type', 'cover', 'user', 'title', 'content','is_recommend',
                                                              'ctime', 'view', 'comments', 'goods',
                                                              'collections').order_by('-ctime')
        if id is None:
            p = LimitPagination()  # 注册分页
            page_user_list = p.paginate_queryset(queryset=res, request=request, view=self)
            ser = BlogSerializer(page_user_list, many=True)  # 可允许多个
            return p.get_paginated_response("200", "获取成功", ser.data)
        else:
            ser = BlogDtailSerializer(res,many=True)
            print(ser)
            response = {'status': 200, 'msg': "查找成功", 'data': ser.data}
            return Response(response)
#点赞
class Goods(APIView):
    def get(self, request, *args, **kwargs):
        response = {'status': "200", 'msg': '点赞成功'}
        user_id = request.user[0]['id']
        user = getUser(user_id)
        blog_id = request.GET.get('blog', None)
        if blog_id is None:
            raise DataFailed({"status": "202", "msg": "未选中博客"})
        blog = getBlog(blog_id)
        is_goods = models.Good.objects.filter(blog=blog, user=user).exists()
        if is_goods:
            raise DataFailed({"status": "201", "msg": "您已点赞该博客"})
        try:
            with transaction.atomic():
                obj = models.Good(blog=blog,user=user)
                obj.save()
                #点赞+1
                blog.goods = F('goods') + 1
                blog.save()
        except Exception as e:
            raise DataFailed({"status": "201", "msg": "点赞异常"})

        get_blog_goods = getBlog(blog_id)
        goods = get_blog_goods.goods
        response['goods'] = goods
        return Response(response)
#评论
class Commtent(APIView):
    def post(self, request, *args, **kwargs):
        try:
            data = json.loads(request.body)
        except:
            raise DataFailed({"status": "203", "msg": "数据结构错误"})
        try:
            blog_id = data['id']
        except:
            raise DataFailed({"status": "201", "msg": "博客不存在"})
        try:
            post_id = data['post_id']
        except:
            post_id = None
        content = data['content']
        if content is "":
            raise DataFailed({"status": "201", "msg": "内容不为空"})
        user_id = request.user[0]['id']
        if blog_id is None:
            raise DataFailed({"status": "201", "msg": "未指定博客"})
        else:
            user = getUser(user_id)
            blog = getBlog(blog_id)
            response = {'status': "200", 'msg': "发布成功"}
            if post_id is None:
                post = None
                topic = 0
            else:
                post = getPost(post_id)
                topic = post.topic + 1
            try:
                with transaction.atomic():
                    obj = models.Comment(blog=blog, user=user, post=post, content=content,topic=topic)
                    obj.save()
                    # 评论+1
                    blog.comments = F('comments') + 1
                    blog.save()
            except Exception as e:
                response = {'status': "201", 'msg': '发布异常'}

            get_blog_comments = getBlog(blog_id)
            comments = get_blog_comments.comments
            response['comments'] = comments

            return Response(response)
#收藏
class Collection(APIView):
    def get(self, request, *args, **kwargs):
        blog_id = request.GET.get('blog', None)
        user_id = request.user[0]['id']
        if blog_id is  None:
            raise DataFailed({"status": "201", "msg": "未指定博客"})
        else:
            #收藏处理
            user = getUser(user_id)
            blog = getBlog(blog_id)
            is_collection = models.Collection.objects.filter(blog=blog, user=user).exists()
            if is_collection:
                raise DataFailed({"status": "201", "msg": "您已收藏该博客"})
            response = {'status': "200", 'msg': "收藏成功"}
            try:
                with transaction.atomic():
                    obj = models.Collection(blog=blog, user=user )
                    obj.save()
                    blog.collections = F('collections') + 1
                    blog.save()
            except Exception as e:
                response = {'status': "201", 'msg': '发布异常'}

            get_blog_collections = getBlog(blog_id)
            collections = get_blog_collections.collections
            response['collections'] = collections

            return Response(response)

#热门博客
class HotBlog(APIView):
    authentication_classes = []
    def get(self, request, *args, **kwargs):
        res = models.Blog.objects.filter(status=1).values('id', 'title', 'ctime').order_by('view','-ctime')[:5]
        ser = BlogHotSerializer(res, many=True)
        response = {'status': "200", 'msg': "查找成功", 'data': ser.data}
        return Response(response)


#判断点赞收藏
class is_operation(APIView):
    def get(self, request, *args, **kwargs):
        blog_id = request.GET.get('blog', None)
        user_id = request.user[0]['id']
        user = getUser(user_id)
        blog = getBlog(blog_id)
        response = {'status': "200", 'msg': '查询成功'}
        data = {}
        is_goods = models.Good.objects.filter(blog=blog, user=user).exists()
        if is_goods:
           data['good'] = 1
        else:
            data['good'] = 0
        is_collection = models.Collection.objects.filter(blog=blog, user=user).exists()
        if is_collection:
            data['collection'] = 1
        else:
            data['collection'] = 0
        response['data'] = data
        return Response(response)



#获取实例
def getUser(id):
    try:
        ret = User.objects.get(id=id)
    except Exception as e:
        raise DataFailed({"status": "202", "msg": "用户不存在"})
    return ret
def getType(id):
    try:
        res = models.Type.objects.get(id=id)
    except:
        raise DataFailed({"status": "202", "msg": "类型不存在"})
    return res
def getBlog(id):
    try:
        ret = models.Blog.objects.get(id=id)
    except:
        raise DataFailed({"status": "202", "msg": "博客不存在"})
    return ret
def getPost(id):
    try:
        ret = models.Comment.objects.get(id=id)
    except:
        raise DataFailed({"status": "202", "msg": "回复不存在"})
    return ret